#!/usr/bin/env bash

declare -r obs_base_url="https://brianhsiung.obs.cn-east-3.myhuaweicloud.com/images/app"
# 私有仓库镜像地址（根据实际情况修改，需要先登录）
declare -r private_registry="registry.cn-east-3.myhuaweicloud.com/eadp"
# 私有镜像Tag（根据实际情况修改）
declare -r private_tag="dev"

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR" || exit 1

log_info()    { echo -e "\033[34m[INFO] $*\033[0m"; }
log_warn()    { echo -e "\033[33m[WARNING] $*\033[0m"; }
log_success() { echo -e "\033[32m[SUCCESS] $*\033[0m"; }
log_error()   { echo -e "\033[31m[ERROR] $*\033[0m"; exit 1; }

if ! command -v wget &>/dev/null; then
    log_error "缺失依赖命令: wget"
fi

if ! command -v docker &>/dev/null; then
    log_error "缺失依赖命令: docker"
fi

get_app() {
    local app_name="$1"
    local app_file="${app_name}.tar.gz"
    local app_url="${obs_base_url}/${arch_type}/${app_name}.tar.gz"

    if [ ! -f "${app_file}" ]; then
        log_info "下载 ${app_file}"
        wget -q "${app_url}" || log_error "下载 ${app_file} 失败"
        #curl -o "${app_file}" "${app_url}" || log_error "下载 ${app_file} 失败"
    else
        log_success "${app_file} 已存在，跳过下载"
    fi
}

main() {

    while :
    do
        read -p "是否下载x86_64架构的镜像 ( Y/y 表示下载x86_64架构的镜像, N/n 表示下载aarch64架构的镜像): " -r option
        case "${option}" in
            Y|y)
                arch_type="x64"
                break
            ;;
            N|n)
                arch_type="aarch64"
                break
            ;;
            *)
                log_warn "无效输入，请输入 Y(y) 或 N(n)"
            ;;
        esac
    done
    
    # 替换掉空格
    sed -i 's/ //g' app_list.txt

    while IFS= read -r line; do
        get_app "${line}"
    done < <(grep -Ev '^#|^$' app_list.txt)

    # 导入镜像
    for var in *.tar.gz; do
        log_info "导入镜像 ${var}"
        sudo docker load -i "${var}" || log_warn "导入 ${var} 失败"
    done

    while :
    do
        read -p "是否要推送镜像到私有镜像仓库 ( Y/y 表示推送镜像到私有镜像仓库, N/n 表示不推送镜像到私有镜像仓库): " -r option
        case "${option}" in
            Y|y)
                for var in $(sudo docker images|grep -v '<none>'|awk '{print $1":"$2}'|sed 1d); do
                    image_name="$(echo "$var"|awk -F '/' '{print $NF}'|awk -F ':' '{print $1}')"
                    new_image_name="${private_registry}/${image_name}:${private_tag}"
                    log_info "推送镜像 ${new_image_name}"
                    sudo docker tag "${var}" "${new_image_name}"
                    sudo docker push "${new_image_name}" || log_warn "推送 ${new_image_name} 失败"
                done
                break
            ;;
            N|n)
                log_success "不推送镜像到私有镜像仓库, 结束！"
                break
            ;;
            *)
                log_warn "无效输入，请输入 Y(y) 或 N(n)"
            ;;
        esac
    done

}

main